//
//  BIDAccessoryFileTableViewController.m
//  商务厅
//
//  Created by mal on 13-12-18.
//  Copyright (c) 2013年 mal. All rights reserved.
//

#import "BIDAccessoryFileTableViewController.h"

@interface BIDAccessoryFileTableViewController ()

@end

@implementation BIDAccessoryFileTableViewController

@synthesize itemsArr;
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"附件列表";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    itemsArr = [[NSMutableArray alloc] initWithCapacity:1];
    [self getFileNames];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    self.itemsArr = nil;
}

//遍历文件名字
- (void)getFileNames
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSArray *urls = [fileManager URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask];
    if(urls.count>0)
    {
        NSError *err;
        NSURL *libraryURL = urls[0];
        NSURL *downloadURL = [libraryURL URLByAppendingPathComponent:@"downloads/doc" isDirectory:YES];
        if([fileManager createDirectoryAtURL:downloadURL withIntermediateDirectories:YES attributes:nil error:&err])
        {
            NSArray *files = [fileManager contentsOfDirectoryAtURL:downloadURL includingPropertiesForKeys:nil options:0 error:&err];
            for(NSURL *fileURL in files)
            {
                NSString *fileName = [fileURL lastPathComponent];
                if([fileName isEqualToString:@".DS_Store"])
                {
                    continue;
                }
                else
                {
                   [itemsArr addObject:fileName];
                }
            }
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [itemsArr count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"identifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [itemsArr objectAtIndex:row];
    [cell setBackgroundColor:[UIColor clearColor]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    [delegate getAccessoryFileName:[itemsArr objectAtIndex:row]];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
